package org.sgx.gwteditors.testgallery.gen;

import java.io.PrintWriter;

import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.typeinfo.JClassType;
import com.google.gwt.core.ext.typeinfo.NotFoundException;
import com.google.gwt.core.ext.typeinfo.TypeOracle;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;

public class Generator1 extends Generator {

	public String generate(TreeLogger logger, GeneratorContext context,
			String typeName) throws UnableToCompleteException {
//		try {
			TypeOracle typeOracle = context.getTypeOracle();			
			JClassType objectType = typeOracle.findType(typeName);			
			String implTypeName = objectType.getSimpleSourceName() + "Impl";			 
	        String implPackageName = objectType.getPackage().getName();
	        
//			PrintWriter printWriter = context.tryCreate(logger, implPackageName, implTypeName);
//			if (printWriter == null)
//				return null;
			
			ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(
	                implPackageName, implTypeName);
	 
	        composerFactory.addImplementedInterface(objectType
	                .getQualifiedSourceName());
	        
	        PrintWriter printWriter = context.tryCreate(logger, implPackageName,
	                implTypeName);
	        if (printWriter != null) {
	 
	            SourceWriter sourceWriter = composerFactory.createSourceWriter(
	                    context, printWriter);
	 
	            writeClassNameMethod(logger, sourceWriter);
	            sourceWriter.commit(logger);
	 
	        }
	        return implPackageName + "." + implTypeName;
	        
	        
//		} catch (NotFoundException e) {
//			logger.log(TreeLogger.ERROR, "Class '" + typeName + "' Not Found",
//					e);
//			throw new UnableToCompleteException();
//		}
	}

//	protected SourceWriter getSourceWriter(TreeLogger logger,
//			GeneratorContext context, String packageName, String className,
//			String superclassName) {
//		
//		PrintWriter printWriter = context.tryCreate(logger, packageName,
//				className);
//		if (printWriter == null)
//			return null;
//		ClassSourceFileComposerFactory composerFactory = new ClassSourceFileComposerFactory(
//				packageName, className);
//		composerFactory.setSuperclass(superclassName);
//		return composerFactory.createSourceWriter(context, printWriter);
//	}
	
	public void writeClassNameMethod(TreeLogger logger, 
			SourceWriter writer) {
//		writer.beginJavaDocComment();
//		writer.println("Overides DashboardComposite getName() method");
//		writer.endJavaDocComment();
		writer.println("public String sayHello()");
		writer.println("{");
		writer.indent();
		writer.println("return \"hello from generator!\";");
		writer.outdent();
		writer.println("}");
	}
}